#!/usr/bin/env bash
#########################
RED=$(printf '\033[31m')
PURPLE=$(printf '\033[0;35m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
BLUE=$(printf '\033[34m')
BOLD=$(printf '\033[1m')
RESET=$(printf '\033[m')
printf "%s\n" "${GREEN}Starting ${YELLOW}vnc server${RESET} ..."
stopvnc -non-stop-dbus 2>/dev/null
TMOE_VNC_DISPLAY_NUMBER=1
export USER="$(whoami)"
export PULSE_SERVER=127.0.0.1
TMOE_LINUX_DIR='/usr/local/etc/tmoe-linux'
TMOE_GIT_DIR="${TMOE_LINUX_DIR}/git"
TMOE_TOOL_DIR="${TMOE_GIT_DIR}/tools"
XSESSION_FILE='/etc/X11/xinit/Xsession'
TMOE_LOCALE_FILE="${TMOE_LINUX_DIR}/locale.txt"
TIGERVNC_CONFIG_FILE='/etc/tigervnc/vncserver-config-defaults'
########################
check_tmoe_locale() {
    if [ -e "${TMOE_LOCALE_FILE}" ]; then
        TMOE_LANG=$(head -n 1 ${TMOE_LOCALE_FILE})
    else
        TMOE_LANG="zh_CN.UTF-8"
    fi
    export LANG="${TMOE_LANG}"
}
###########
check_current_user_name_and_group() {
    CURRENT_USER_NAME=$(sed -n p /etc/passwd | grep "${HOME}" | awk -F ':' '{print $1}' | head -n 1)
    CURRENT_USER_GROUP=$(sed -n p /etc/passwd | grep "${HOME}" | awk -F ':' '{print $5}' | cut -d ',' -f 1 | head -n 1)
    if [ -z "${CURRENT_USER_GROUP}" ]; then
        CURRENT_USER_GROUP=${CURRENT_USER_NAME}
    fi
}
###############
fix_vnc_permissions() {
    check_current_user_name_and_group
    CURRENT_USER_VNC_FILE_PERMISSION=$(ls -l ${HOME}/.vnc/passwd | awk -F ' ' '{print $3}')
    case ${CURRENT_USER_VNC_FILE_PERMISSION} in
    ${CURRENT_USER_NAME}) ;;
    *)
        printf "%s\n" "检测到${HOME}/.vnc/passwd文件所属非当前用户（${CURRENT_USER_NAME}），为避免权限问题，正在将${HOME}目录下的.vnc 的权限归属修改为${CURRENT_USER_NAME}用户和${CURRENT_USER_GROUP}用户组"
        cd ${HOME}
        sudo -E chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} .vnc || su -c "chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} .vnc"
        for i in ".ICEauthority" ".Xauthority"; do
            if [ -e "${i}" ]; then
                sudo -E chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} "${i}" || su -c "chown -Rv ${CURRENT_USER_NAME}:${CURRENT_USER_GROUP} ${i}"
            fi
        done
        unset i
        ;;
    esac
}
##############
tmoe_vnc_preconfigure() {
    check_tmoe_locale
    if [ ! -s "${HOME}/.vnc/passwd" ]; then
        sudo -E cp -rvf "/root/.vnc" "${HOME}" || su -c "cp -rvf /root/.vnc ${HOME}"
        if [ ! -e "${HOME}/.vnc/passwd" ]; then
            cd ${TMOE_TOOL_DIR}
            git reset --hard origin/master
            git pull --rebase --stat origin master --allow-unrelated-histories || git rebase --skip
            debian-i -passwd
        fi
    fi
    fix_vnc_permissions
    if [ "$(uname -r | cut -d '-' -f 3)" = "Microsoft" ] || [ "$(uname -r | cut -d '-' -f 2)" = "microsoft" ]; then
        . ${TMOE_LINUX_DIR}/wsl_pulse_audio
    fi
}
###############
display_vnc_ip_addr() {
    #CURRENT_PORT=$(sed -n p /usr/local/bin/startvnc | grep '\-geometry' | awk -F ' ' '$0=$NF' | cut -d ':' -f 2 | tail -n 1)
    CURRENT_PORT=${TMOE_VNC_DISPLAY_NUMBER}
    CURRENT_VNC_PORT=$((${CURRENT_PORT} + 5900))
    TMOE_IP_ADDR=$(ip -4 -br -c a | awk '{print $NF}' | cut -d '/' -f 1 | grep -v '127\.0\.0\.1' | sed "s@\$@:${CURRENT_VNC_PORT}@")
    case ${TMOE_LANG} in
    zh_*UTF-8)
        cat <<-EOF
正在启动vnc服务,${YELLOW}本机${RESET}vnc地址 ${BLUE}localhost${GREEN}:${CURRENT_VNC_PORT}${RESET}
The LAN VNC address ${YELLOW}局域网${RESET}地址 ${TMOE_IP_ADDR}
EOF
        ;;
    *)
        cat <<-EOF
The ${YELLOW}local${RESET} vnc address is ${BLUE}localhost${GREEN}:${CURRENT_VNC_PORT}${RESET}
The ${YELLOW}LAN${RESET} vnc address is ${TMOE_IP_ADDR}
EOF
        ;;
    esac

}
############
start_tmoe_xvnc() {
    . ${TIGERVNC_CONFIG_FILE} 2>/dev/null
    if [[ $(readlink /etc/alternatives/vncserver) = "/usr/bin/tigervncserver" || -n $(command -v vncsession) ]]; then
        set -- "${@}" "-ZlibLevel=0"
    fi
    #tightvnc专有参数bc #enable bug compatibility #set -- "${@}" "bc"
    set -- "${@}" "-a" "5"
    set -- "${@}" "-wm"
    set -- "${@}" "-alwaysshared"
    set -- "${@}" "-geometry" "${geometry}"
    set -- "${@}" "-once"
    set -- "${@}" "-depth" "16"
    set -- "${@}" "-deferglyphs" "16"
    set -- "${@}" "-rfbauth" "${HOME}/.vnc/passwd"
    set -- "${@}" "-desktop" "${desktop}"
    set -- "${@}" ":${TMOE_VNC_DISPLAY_NUMBER}"
    set -- "Xvnc" "${@}"
    "${@}" &
    export DISPLAY=:${TMOE_VNC_DISPLAY_NUMBER}
    . ${XSESSION_FILE} &>/dev/null &
    exit 0
}
##############
source_tmoe_dbus_daemon() {
    . ${TMOE_TOOL_DIR}/gui/launch_dbus_daemon
}
###########
check_vncsession() {
    if [ $(command -v vncsession) ]; then
        case $(id -u) in
        0)
            vncsession $(whoami) :${TMOE_VNC_DISPLAY_NUMBER}
            exit 0
            ;;
        *) check_xvnc ;;
        esac
    else
        check_xvnc
    fi
}
#########
check_xvnc() {
    if [ $(command -v Xvnc) ]; then
        start_tmoe_xvnc
        exit 0
    fi
}
##########
tmoe_vnc_preconfigure
source_tmoe_dbus_daemon
display_vnc_ip_addr
#check_vncsession
check_xvnc
##########
#最后一行命令已废弃，仅作兼容性测试，直接修改其参数值可能不会生效。
#20200912注:tigervnc-1.11.0-2及其之后的版本，可能无法使用旧版命令。
vncserver -geometry 1440x720 -depth 24 -name tmoe-linux :1
